<?php

namespace model;

use entity\db\EntityCoreSession;
use lib\tools\db\BaseDb;

class SessionDb
{
    const _TABLE_ = 'core_session';

    /**
     * @param EntityCoreSession $entity
     * @throws \Exception
     */
    public static function save(EntityCoreSession $entity)
    {
        $entity->uid = \Yaf_Session::getInstance()->get('uid') ?: 0;

        if (is_array($entity->content)) $entity->content = json_encode($entity->content, JSON_UNESCAPED_UNICODE);

        if (self::count(['session_id' => $entity->session_id, 'status' => self::STATUS_NORMAL])) {
            //update
            $data = [
                'uid' => $entity->uid,
                'content' => $entity->content,
                'editTime' => self::dbTime(),
            ];
            self::update($data, ['session_id' => $entity->session_id, 'status' => self::STATUS_NORMAL])->rowCount();
        } else {
            $entity->status = self::STATUS_NORMAL;
            $entity->addTime = self::dbTime();
            self::insert($entity);
        }
    }

    public static function getBySessionId($session_id)
    {
        $rs = self::get('content', ['session_id' => $session_id, 'status' => self::STATUS_NORMAL]);

        return $rs;
    }

}